package com.easygoods.tasks;

import com.bestvike.stone.core.lang.Convert;
import com.easygoods.entity.MissionInfo;
import com.easygoods.entity.MissionTeam;
import com.easygoods.enums.MissionTeamState;
import com.easygoods.service.MissionService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by 许崇雷 on 2019-02-27.
 */
@Component
@CommonsLog
public class MissionSettleScheduling {
    private static final int PAGE_SIZE = 50;

    @Autowired
    private MissionService missionService;

    //4个小时执行一次
    @Scheduled(fixedDelay = 4 * 60 * 60 * 1000)
    public void settleMissions() {
        log.info("============开始任务批量结算");
        final List<MissionInfo> toSettleMissionList = this.missionService.getToSettleMissionList();
        for (MissionInfo missionInfo : toSettleMissionList) {
            log.info("开始结算任务 missionId:" + missionInfo.getId());
            try {
                this.settleMission(missionInfo);
                log.info("任务结算成功 missionId:" + missionInfo.getId());
            } catch (Exception e) {
                log.error("任务结算出错 missionId:" + missionInfo.getId(), e);
            }
        }
        log.info("============任务批量结算完成");
    }

    //结算单个任务
    private void settleMission(MissionInfo missionInfo) {
        log.info("====任务结算开始 missionId:" + missionInfo.getId());
        int pageNum = 1;
        List<MissionTeam> missionTeamList = this.missionService.getTeamListByMission(missionInfo, pageNum, PAGE_SIZE);
        while (missionTeamList.size() > 0) {
            for (MissionTeam missionTeam : missionTeamList) {
                log.info("开始结算团队 teamId:" + missionTeam.getId());
                final MissionTeamState state = Convert.toType(missionTeam.getState(), MissionTeamState.class);
                if (state == MissionTeamState.Settled) {
                    log.info("该团队已结算,跳过 teamId:" + missionTeam.getId());
                    continue;
                }

                try {
                    this.missionService.settleTeam(missionInfo, missionTeam);
                } catch (Exception e) {
                    log.error("团队结算出错 teamId:" + missionTeam.getId(), e);
                }
            }

            pageNum++;
            missionTeamList = this.missionService.getTeamListByMission(missionInfo, pageNum, PAGE_SIZE);
        }
        this.missionService.trySetMissionSettled(missionInfo.getId());
        log.info("====任务结算完成 missionId:" + missionInfo.getId());
    }
}
